// {{ AURA-X: 完全重写 - 实现三种自动化流程. Approval: 寸止 }}

// {{ AURA-X: Modify - 修复PKCE code_challenge生成. Approval: 寸止 }}
// 生成PKCE code verifier
function generateCodeVerifier() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
  let verifier = '';
  for (let i = 0; i < 43; i++) {
    verifier += chars[Math.floor(Math.random() * chars.length)];
  }
  return verifier;
}

// 生成PKCE code challenge (SHA256 + base64url)
async function generateCodeChallenge(verifier) {
  const encoder = new TextEncoder();
  const data = encoder.encode(verifier);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashBase64 = btoa(String.fromCharCode.apply(null, hashArray));
  // 转换为base64url格式
  return hashBase64
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}

// 生成状态码
function generateState() {
  return Math.random().toString(36).substring(2, 15);
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {

  // {{ AURA-X: Add - 获取auth.augmentcode.com的session. Approval: 寸止 }}
  // 获取auth.augmentcode.com的Cookies
  if (request.action === 'getAuthCookies') {
    (async () => {
      try {
        console.log('[Background] Getting cookies for auth.augmentcode.com');

        const domain = 'auth.augmentcode.com';
        const cookies = await chrome.cookies.getAll({ domain });

        // 查找session cookie (可能是 session 或其他名称)
        let sessionCookie = cookies.find(c => c.name === 'session') ||
                           cookies.find(c => c.name === '_session') ||
                           cookies.find(c => c.name.includes('session'));

        if (sessionCookie) {
          console.log(`[Background] ✅ Found ${sessionCookie.name} in auth.augmentcode.com`);
          console.log(`[Background] Session:`, sessionCookie.value);
        } else {
          console.warn(`[Background] ❌ No session cookie found in ${domain}`);
        }

        sendResponse({
          success: true,
          session: sessionCookie ? sessionCookie.value : null,
          cookieName: sessionCookie ? sessionCookie.name : null,
          domain: sessionCookie ? sessionCookie.domain : null
        });
      } catch (error) {
        console.error('[Background] Failed to get auth cookies:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }

  // {{ AURA-X: Modify - 修复Cookie获取逻辑. Approval: 寸止 }}
  // 获取Cookies (app.augmentcode.com的_session)
  if (request.action === 'getCookies') {
    (async () => {
      try {
        console.log('[Background] Getting cookies for .augmentcode.com');

        // {{ AURA-X: Modify - 优先从app.augmentcode.com获取_session. Approval: 寸止 }}
        const domains = ['app.augmentcode.com', '.augmentcode.com', 'augmentcode.com'];
        let sessionCookie = null;

        for (const domain of domains) {
          try {
            const cookies = await chrome.cookies.getAll({ domain });

            // 严格匹配 _session
            const found = cookies.find(c => c.name === '_session');
            if (found) {
              sessionCookie = found;
              console.log(`[Background] ✅ Found _session in ${domain}`);
              console.log(`[Background] _session:`, found.value);
              break;
            }
          } catch (e) {
            console.warn(`[Background] Failed to get cookies for ${domain}:`, e);
          }
        }

        sendResponse({
          success: true,
          session: sessionCookie ? sessionCookie.value : null,
          domain: sessionCookie ? sessionCookie.domain : null
        });
      } catch (error) {
        console.error('[Background] Failed to get cookies:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }

  // {{ AURA-X: Add - 获取auth.augmentcode.com的session cookie. Approval: 寸止 }}
  // 获取auth.augmentcode.com的session cookie
  if (request.action === 'getAuthSessionCookie') {
    (async () => {
      try {
        console.log('[Background] Getting session cookie from auth.augmentcode.com');

        const cookies = await chrome.cookies.getAll({ domain: 'auth.augmentcode.com' });

        // 查找session cookie
        const sessionCookie = cookies.find(c => c.name === 'session');

        if (sessionCookie) {
          console.log(`[Background] ✅ Found session in auth.augmentcode.com`);
          console.log(`[Background] session:`, sessionCookie.value);
          sendResponse({
            success: true,
            session: sessionCookie.value
          });
        } else {
          console.warn('[Background] ❌ No session cookie found in auth.augmentcode.com');
          sendResponse({
            success: false,
            error: 'No session cookie found'
          });
        }
      } catch (error) {
        console.error('[Background] Failed to get auth session:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  
  // 仅注册
  if (request.action === 'registerOnly') {
    (async () => {
      const codeVerifier = generateCodeVerifier();
      const codeChallenge = await generateCodeChallenge(codeVerifier);
      const state = generateState();
      
      console.log('[Background] Register only:', { codeVerifier, codeChallenge, state });
      
      // 构建Augment OAuth授权URL
      const authUrl = `https://auth.augmentcode.com/authorize?` +
        `response_type=code&` +
        `code_challenge=${codeChallenge}&` +
        `client_id=v&` +
        `state=${state}&` +
        `prompt=login`;
      
      console.log('[Background] Opening:', authUrl);
      
      chrome.tabs.create({
        url: authUrl,
        active: true
      }, (tab) => {
        chrome.storage.local.set({
          currentAction: 'registerOnly',
          currentTabId: tab.id,
          currentData: request.data,
          codeVerifier,
          state
        });
        console.log('[Background] Tab created:', tab.id);
        sendResponse({ success: true });
      });
    })();
    
    return true;
  }
  
  // 仅绑卡
  if (request.action === 'bindCardOnly') {
    // 假设已经登录，直接打开Dashboard
    chrome.tabs.create({
      url: 'https://www.augmentcode.com/dashboard/billing',
      active: true
    }, (tab) => {
      chrome.storage.local.set({
        currentAction: 'bindCardOnly',
        currentTabId: tab.id,
        currentData: request.data
      });
      sendResponse({ success: true });
    });
    
    return true;
  }
  
  // 注册+绑卡
  if (request.action === 'registerAndBind') {
    (async () => {
      const codeVerifier = generateCodeVerifier();
      const codeChallenge = await generateCodeChallenge(codeVerifier);
      const state = generateState();
      
      const authUrl = `https://auth.augmentcode.com/authorize?` +
        `response_type=code&` +
        `code_challenge=${codeChallenge}&` +
        `client_id=v&` +
        `state=${state}&` +
        `prompt=login`;
      
      console.log('[Background] Register and bind, opening:', authUrl);
      
      chrome.tabs.create({
        url: authUrl,
        active: true
      }, (tab) => {
        chrome.storage.local.set({
          currentAction: 'registerAndBind',
          currentTabId: tab.id,
          currentData: request.data,
          codeVerifier,
          state,
          flowStep: 'register'
        });
        sendResponse({ success: true });
      });
    })();
    
    return true;
  }
  
  // 步骤完成通知
  if (request.action === 'stepComplete') {
    chrome.storage.local.get(['currentAction', 'flowStep', 'currentData'], async (data) => {
      console.log('Step complete:', request.step, 'Current action:', data.currentAction);
      
      // 如果是注册+绑卡流程，注册完成后转到绑卡
      if (data.currentAction === 'registerAndBind' && request.step === 'register') {
        // 等待一会儿，然后打开绑卡页面
        setTimeout(() => {
          chrome.tabs.create({
            url: 'https://www.augmentcode.com/dashboard/billing',
            active: true
          }, (tab) => {
            chrome.storage.local.set({
              currentTabId: tab.id,
              flowStep: 'bind'
            });
          });
        }, 2000);
      }

      // 如果是仅注册流程，注册完成后跳转到 subscription 页面
      if (data.currentAction === 'registerOnly' && request.step === 'register') {
        // 等待一会儿，然后打开 subscription 页面
        setTimeout(() => {
          chrome.tabs.create({
            url: 'https://app.augmentcode.com/account/subscription',
            active: true
          }, (tab) => {
            chrome.storage.local.set({
              currentTabId: tab.id,
              flowStep: 'subscription'
            });
          });
        }, 2000);
      }
    });
    
    sendResponse({ success: true });
    return true;
  }
});

// 监听标签页更新
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
  if (changeInfo.status === 'complete') {
    chrome.storage.local.get(['currentTabId', 'currentAction'], (data) => {
      if (data.currentTabId === tabId) {
        // 通知content script页面已加载
        chrome.tabs.sendMessage(tabId, {
          action: 'pageReady',
          currentAction: data.currentAction
        }).catch(err => {
          console.log('Content script not ready yet:', err);
        });
      }
    });
  }
});

